const Mock = require('mockjs');
const Utils = require('./utils');

const BASE_DIR = '../template/';

let routes = [];
let router = null;

module.exports = app = {
  // 将模板文件加载为路由
  loadRoutes(r) {
    router = r;
    let jsonFiles = Utils.getDirFiles(BASE_DIR);
    jsonFiles.forEach(jf => {
      let interPath = `/${jf.replace(/-/g, '/')}`;
      this.registerRouter(interPath, jf);
      routes.push(interPath);
    })
  },
  // 监听template文件夹
  watch() {
    Utils.watchDir(BASE_DIR, filename => {
      let path = filename.replace(/-/g, '/')
      if (routes.indexOf(path) === -1) {
        this.registerRouter(path, filename);
      }
    });
  },
  // 路由注册
  registerRouter(interPath, filename) {
    router.get(interPath, (req, res) => {
      let json = Utils.getJsonFile(`${BASE_DIR}${filename}.json`);
      res.json(Mock.mock(json));
    })
    console.log(`添加接口: ${interPath}, 状态: OK.`);
  }
}